package logic

import (
	"context"
	"errors"
	"guar/model/mysql"

	"guar/guarrpc/guarrpc"
	"guar/guarrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateLogic) Create(in *guarrpc.CreateRequest) (*guarrpc.CreateResponse, error) {
	// todo: add your logic here and delete this line

	var shops mysql.Shop
	mysql.DB.Debug().Where("shop_no = ?", in.ShopNo).Find(&shops)
	if shops.ID != 0 {
		return nil, errors.New("当前商品已存在，请更换")
	}

	shop := mysql.Shop{
		ShopNo: in.ShopNo,
		Desc:   in.Desc,
		Price:  float64(in.Price),
		UserId: int(in.UserId),
	}

	err := mysql.DB.Debug().Create(&shop).Error
	if err != nil {
		return nil, err
	}
	/*
		SELECT
		  *
		FROM
		  shops
			LEFT JOIN users ON user_id = shops.user_id
	*/

	mysql.DB.Select("shops").
		Joins("LEFT JOIN users ON user_id = shops.user_id").
		Find(&shops)

	return &guarrpc.CreateResponse{
		ShopId: int64(shop.ID),
	}, nil
}
